#include "include/cardsreader.h"
#include <QFile>
#include <Qt>

#include "include/treeitem.h"
#include "include/Deck.h"


const qint32 CardsReader::MagicNumber = -1;
const quint32 CardsReader::CurrentReaderVersion = 2;

CardsReader::CardsReader()
{
}

void CardsReader::readFrom(QDataStream& stream, TreeItem& destRoot)
{
	qint32 magicNumber;
	stream >> magicNumber;
	if (magicNumber == MagicNumber) //versioning supported
	{
		quint32 version;
		stream >> version;

		switch (version)
		{

		case 1:
		{
			Deck* pDeck = destRoot.getDeck();
			pDeck->readFromVer1(stream);
			destRoot.readFrom(stream);
			break;
		}

		case CurrentReaderVersion:
		{
			Deck* pDeck = destRoot.getDeck();
			pDeck->readFromVer2(stream);
			destRoot.readFrom(stream);
			break;
		}

		default:
		{
			return;
		}

		}

	}
	else //initial version with no version info
	{
		int cardsCount = magicNumber;
		Deck* pDeck = destRoot.getDeck();

		pDeck->readFromVer0(stream, cardsCount);
		destRoot.readVer0(stream);
	}
}


void CardsReader::readFrom(QString path, TreeItem& destRoot)
{
	QFile deckfile(path);
	deckfile.open(QIODevice::ReadOnly);
	QDataStream in(&deckfile);
	readFrom(in, destRoot);
}
